package com.raychi.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.raychi.demo.entity.Buyer;
import com.raychi.demo.util.BuyerUtil;

public class BuyerDao {
	public List<Buyer> getBuyers(Connection conn) throws ClassNotFoundException, SQLException{
		List<Buyer> buyers = new ArrayList<Buyer>();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from Buyer");
		Buyer buyer = null;
		while(rs.next()){
			buyer = BuyerUtil.createBuyer(rs);
			buyers.add(buyer);
		}
		return buyers;
	}
	
	public void delete(Buyer buyer, Connection conn) throws Exception{
		Statement st = conn.createStatement();
		String sql = "delete from buyer where id=" + buyer.getId();
		st.execute(sql);
	}
	
	public void save(Buyer buyer, Connection conn) throws Exception{
		String sql = "insert into buyer (name,money) values (?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, buyer.getName());
		ps.setFloat(2, buyer.getMoney());
		ps.execute();
	}
	
	public void update(Buyer buyer, Connection conn) throws Exception{
		String sql = "update buyer set name = ?,money = ? where id =?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, buyer.getName());
		ps.setFloat(2, buyer.getMoney());
		ps.setInt(3, buyer.getId());
		ps.executeUpdate();
	}
}
